package com.anxinr.interceptor;

import com.anxinr.constant.RedisConstant;
import com.anxinr.enums.ExceptionEnum;
import com.anxinr.exception.LogicException;
import com.anxinr.util.JWTUtils;
import com.anxinr.util.RedisUtil;
import com.anxinr.util.UserInfoContext;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器拦截处理方式
 *
 * @author anxinr
 */
@Slf4j
@Component
public class StudyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        try {
            /**查看是否登录*/
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                throw new LogicException(ExceptionEnum.STUDY_USER_NAME_ERROR);
            }
            /**解析token*/
            String jwt = JWTUtils.parseJWT(token);
            /**把用户信息存入ThreadLocal中*/
            UserInfoContext.setUserInfo(redisUtil.getUserInfo(RedisConstant.USER_TOKEN_INFO + jwt));
            /**处理跨域请求*/
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
        }catch (Exception e){
            log.info("捕抓到位置异常，异常信息 -> {}",e.getMessage());
            throw e ;
        }
        return false;
    }
}
